<template>
  <div class="app-container">
      <!--查询栏-->
      <el-form :inline="true"
               v-if="advanced"
               :model="userCardQuery"
               class="demo-form-inline">

        <el-form-item label="会员姓名" prop="name">
          <el-input v-model="userCardQuery.name" placeholder="请输入参与人姓名"></el-input>
        </el-form-item>

        <el-form-item label="会员联系方式" prop="mobile">
          <el-input v-model="userCardQuery.mobile" placeholder="请输入参与人联系方式"></el-input>
        </el-form-item>

        <el-form-item label="会员卡号类型" prop="mobile">
          <el-input v-model="userCardQuery.cardType" placeholder="会员卡号类型"></el-input>
        </el-form-item>

        <el-form-item label="会员卡号" prop="mobile">
          <el-input v-model="userCardQuery.cardNum" placeholder="会员卡号"></el-input>
        </el-form-item>

      </el-form>

      <!-- 操作 -->
      <div>
         <span class="table-page-search-submitButtons">

            <span class="submitButtons-left">
              <el-button size="small" type="success" @click="addUserCard" icon="el-icon-plus" plain>新增</el-button>
              <el-button size="small" :loading="downloadLoading" @click="handleDownload" icon="el-icon-download">导出</el-button>
            </span>

            <span class="submitButtons-right">
              <el-button size="small" type="primary" @click="submitUserCardQuery" icon="el-icon-search" plain>查询</el-button>
              <el-button size="small" @click="resetUserCardQuery" icon="el-icon-refresh">重置</el-button>
              <a @click="toggleAdvanced" style="margin-left: 8px; color: #00BFFF; font-size: 14px">
                {{ advanced ? '收起' : '展开' }}
                <i :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />
              </a>
            </span>

         </span>
      </div>

      <!--表格-->
      <el-table v-loading="isLoading"
                :data="userCardList"
                element-loading-text="数据加载中"
                border
                fit
                @selection-change="handleSelectionChange"
                ref="multiplePublishActTable"
                highlight-current-row>

        <el-table-column type="selection" width="44" align="center"></el-table-column><!--选择一行-->
        <el-table-column prop="id" label="会员编号" width="90" align="center"></el-table-column>
        <el-table-column prop="name" label="会员姓名" width="100" align="center"></el-table-column>
        <el-table-column prop="openCardTime" label="开卡时间" width="200" align="center"></el-table-column>
        <el-table-column prop="cardType" label="会员卡类型" width="110" align="center"></el-table-column>
        <el-table-column prop="cardNum" label="会员卡号" width="160" align="center"></el-table-column>
        <el-table-column prop="mobile" label="会员手机号" width="120" align="center"></el-table-column>
        <el-table-column label="性别" width="80" align="center">
          <template slot-scope="scope">
            {{scope.row.sex ==="0" ? "男":"女" }}
          </template>
        </el-table-column>

        <el-table-column label="开卡状态" width="60" align="center">
          <template slot-scope="scope">
            {{scope.row.status ==="1" ? "正常":"停用"}}
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">

          <template slot-scope="scope">

            <el-button type="primary" @click="updateUserCard(scope.row)" size="mini" icon="el-icon-edit" round plain>修改</el-button>

            <el-button size="mini" type="primary" @click="queryUserIntegral(scope.row)" round plain>积分明细</el-button>

            <el-button size="small" :type="scope.row.status == 1 ? 'danger':'primary'"
              @click="handleUse(scope.row)" round plain
            > {{scope.row.status == 1 ? "停用" : "启用"}}
            </el-button>

            <el-button type="danger" size="mini" icon="el-icon-delete"
                       @click="removeUserCard(scope.row)" round plain>删除
            </el-button>

          </template>
        </el-table-column>

      </el-table>

      <!--分页器-->
      <el-pagination
        background
        :current-page="queryParams.currentPage"
        :page-size="queryParams.limit"
        :total="userCardListTotal"
        style="padding: 60px 0; text-align: center;"
        layout="total, prev, pager, next, jumper"
        @current-change="getUserCardList"
      />

      <!--新增会员卡对话框-->
      <el-dialog :title="title" @close="addActCancel" :visible.sync="addVisible" width="800px" append-to-body>
        <el-form :model="addForm" ref="addForm" label-width="120px" :rules="updateUserCardRules">

          <el-form-item label="会员姓名" prop="name" width="100px">
            <el-input placeholder="请选择" v-model="addForm.name"/>
          </el-form-item>

          <el-form-item label="开卡时间" prop="openCardTime">
            <el-date-picker v-model="addForm.openCardTime"
                            type="datetime"
                            style="width: 100%"
                            placeholder="开卡时间"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            default-time="00:00:00"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="会员卡类型" prop="cardType" width="100px">
            <el-input placeholder="请选择" v-model="addForm.cardType"/>
          </el-form-item>

          <el-form-item label="会员卡号" prop="cardNum" width="100px">
            <el-input placeholder="请选择" v-model="addForm.cardNum"/>
          </el-form-item>

          <el-form-item label="会员手机号" prop="mobile" width="100px">
            <el-input placeholder="请选择" v-model="addForm.mobile"/>
          </el-form-item>

          <el-form-item label="性别" prop="sex" width="100px">
            <el-input placeholder="请选择" v-model="addForm.sex"/>
          </el-form-item>

          <el-form-item label="开卡状态" prop="status" width="100px">
            <el-input placeholder="请选择" v-model="addForm.status"/>
          </el-form-item>

        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitAddUserCard">保存</el-button>
          <el-button @click="addUserCardCancel">取 消</el-button>
        </div>

      </el-dialog>


      <!--修改会员卡对话框-->
      <el-dialog :title="title" @close="updateActCancel" :visible.sync="updateVisible" width="800px" append-to-body>
        <el-form :model="updateForm" ref="updateForm" label-width="120px" :rules="updateUserCardRules">

          <el-form-item label="会员姓名" prop="name" width="100px">
            <el-input placeholder="请选择" v-model="updateForm.name"/>
          </el-form-item>

          <el-form-item label="开卡时间" prop="openCardTime" width="100px">
            <el-input placeholder="请选择" v-model="updateForm.openCardTime"/>
          </el-form-item>

          <el-form-item label="会员卡类型" prop="cardType" width="100px">
            <el-input placeholder="请选择" v-model="updateForm.cardType"/>
          </el-form-item>

          <el-form-item label="会员卡号" prop="cardNum" width="100px">
            <el-input placeholder="请选择" v-model="updateForm.cardNum"/>
          </el-form-item>

          <el-form-item label="会员手机号" prop="mobile" width="100px">
            <el-input placeholder="请选择" v-model="updateForm.mobile"/>
          </el-form-item>

          <el-form-item label="性别" prop="sex" width="100px">
            <el-input placeholder="请选择" v-model="updateForm.sex"/>
          </el-form-item>

          <el-form-item label="开卡状态" prop="status" width="100px">
            <el-input placeholder="请选择" v-model="updateForm.status"/>
          </el-form-item>

        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitUpdateUserCard">保存</el-button>
          <el-button @click="updateUserCardCancel">取 消</el-button>
        </div>

      </el-dialog>


      <!--查看会员积分明细对话框-->
      <el-dialog :title="title" @close="queryUserIntegralCancel" :visible.sync="queryUserIntegralVisible" width="1200px" append-to-body>

        <!--查询栏-->
        <el-form :inline="true"
                 :model="userIntegralQuery"
                 class="demo-form-inline">

          <el-form-item label="参与的活动详情" prop="detail">
            <el-input v-model="userIntegralQuery.detail" placeholder="请输入积分详情"></el-input>
          </el-form-item>

          <el-form-item label="积分数量" prop="integralNum">
            <el-input v-model="userIntegralQuery.integralNum" placeholder="请输入积分数量"></el-input>
          </el-form-item>

          <el-form-item label="获得积分的日期" prop="createTime">
            <el-input v-model="userIntegralQuery.createTime" placeholder="请输入获得积分的日期"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button size="small" type="primary" @click="getIntegralList" icon="el-icon-search" plain>查询</el-button>
            <el-button size="small" @click="resetIntegralQuery" icon="el-icon-refresh">重置</el-button>
          </el-form-item>

        </el-form>

        <!--表格-->
        <el-table v-loading="isLoading"
                  :data="integralList"
                  element-loading-text="数据加载中"
                  border
                  fit
                  highlight-current-row>

          <el-table-column prop="nickname" label="会员名" align="center"></el-table-column>
          <el-table-column prop="detail" label="参与的活动详情" align="center"></el-table-column>
          <el-table-column prop="integralNum" label="积分数量" align="center"></el-table-column>
          <el-table-column prop="createTime" label="获得积分的日期" align="center"></el-table-column>
        </el-table>

        <!--分页器-->
        <el-pagination
          background
          :current-page="IntegralQueryParams.currentPage"
          :page-size="IntegralQueryParams.limit"
          :total="integralListTotal"
          style="padding: 60px 0; text-align: center;"
          layout="total, prev, pager, next, jumper"
          @current-change="getIntegralList"
        />

        <div slot="footer" class="dialog-footer" style="margin-top: -134px">
          <el-button size="small" @click="closeUserCard" icon="el-icon-refresh">关闭</el-button>
        </div>

      </el-dialog>
  </div>
</template>

<script>
  import userCard from '@/api/userCard/userCard'
  import integral from '@/api/userCard/integral'
  export default
  {
    name:"hyList",
    data()
    {
      //性别输入检查
      let sexValidate =(rule,value,callback)=>
      {
        if(!value)
        {
          return callback(new Error('性别不能为空'));
        }
        if(value !=="男" && value !=="女")
        {
          return callback(new Error('性别只能为男或女'));
        }else
        {
          return callback();
        }
      };
      //开卡状态输入检查
      let statusValidate =(rule,value,callback)=>
      {
        if(!value)
        {
          return callback(new Error('开卡状态不能为空'));
        }
        if(value !=="启用" && value !=="停用")
        {
          return callback(new Error('开卡状态只能为启用或停用'));
        }else
        {
          return callback();
        }
      };
      return {
        cardNum:"",//积分明细查询的会员卡卡号
        userIntegralQuery://积分明细查询条件
        {
          detail:"",
          integralNum:"",
          createTime:""
        },
        integralList:[],//会员卡积分明细
        integralListTotal:0,//会员卡积分总记录数
        //选择哪一行会员列表
        multipleSelection: [],
        filename: "会员卡信息",//
        autoWidth: true,//excel表格宽度
        bookType: "xlsx",//excel后缀名
        downloadLoading:false,
        addVisible:false,//新增会员卡对话框是否可见
        queryUserIntegralVisible:false,//查询会员卡积分明细对话框是否可见
        // 高级搜索 展开true/关闭false
        advanced: false,
        addForm: { //新增会员卡表单
          name:"",
          openCardTime:"",
          cardType:"",
          cardNum:"",
          mobile:"",
          sex:"",
          status:""
        },
        updateForm: { //修改会员卡表单
          name:"",
          openCardTime:"",
          cardType:"",
          cardNum:"",
          mobile:"",
          sex:"",
          status:""
        },
        updateVisible: false,//修改会员卡对话框是否可见
        isLoading: true, //是否正在加载
        queryParams: //分页查询参数
          {
            currentPage: 1,
            limit: 4,
          },
        IntegralQueryParams: //分页查询参数
          {
            currentPage: 1,
            limit: 4,
          },
        title: "",

        //所有的会员卡列表
        userCardLists: [],
        //会员卡列表
        userCardList: [],

        //会员卡查询可见性
        queryUserCardVisible: false,

        //会员卡列表总记录数
        userCardListTotal: 0,

        //会员卡查询条件
        userCardQuery:
          {
            name: "",
            mobile: ""
          },

        //是否禁用参与人姓名，参与人联系方式
        editUserCard: false,

        //选择哪一行会员卡列表
        multipleUserCardSelection: [],

        //会员卡的检查规则
        updateUserCardRules:
        {
          name:
            [
              { required: true, message: "会员卡名字不能为空！", trigger: "change" }
            ],
          openCardTime:
            [
              { required: true, message: "会员卡开卡时间不能为空！", trigger: "change" }
            ],
          cardType:
            [
              { required: true, message: "会员卡类型不能为空！", trigger: "change" }
            ],
          cardNum:
            [
              { required: true, message: "会员卡卡号不能为空！", trigger: "change" }
            ],
          mobile:
            [
              { required: true, message: "会员手机号不能为空！", trigger: "change" }
            ],
          sex:
            [
              { required:true,  validator:sexValidate, trigger: "blur" }
            ],
          status:
            [
              { required: true, validator:statusValidate, trigger: "change" }
            ]
        },
      }
    },
    methods:
      {
        //查看会员积分明细
        queryUserIntegral(row)
        {
          this.cardNum = row.cardNum;
          this.queryUserIntegralVisible = true;
          this.getIntegralList();
        },
        //选中活动的一行时的事件
        handleSelectionChange(val)
        {
          this.multipleSelection = val;
        },
        //导出
        handleDownload()
        {
          if(this.multipleSelection.length ===0)
          {
            this.$message.warning("请勾选要导出的会员卡!");
            return;
          }
          this.$message.success("将导出已勾选的会员卡");
          let that = this;
          let list = [];
          this.multipleSelection.forEach((item)=>
          {
            item.sex = item.sex==="0"?"男":"女";
            list.push(item);
          })
          setTimeout(()=>
          {
            that.downloadLoading = true
            import('@/vendor/Export2Excel').then(excel =>
            {
              const tHeader = ['会员卡号','联系方式','会员姓名','会员性别'];//导出的excel表
              const filterVal = ['cardNum', 'mobile', 'name', 'sex'];//table属性
              const data = this.formatJson(filterVal, list);
              excel.export_json_to_excel({
                header: tHeader,
                data,
                filename: this.filename,
                autoWidth: this.autoWidth,
                bookType: this.bookType
              })
              that.downloadLoading = false
            })
          },1200);
          this.multipleSelection = [];
          //清除选中的活动
          this.$refs.multiplePublishActTable.clearSelection();
        },
        formatJson(filterVal, jsonData)
        {
          return jsonData.map(v => filterVal.map(j => {
            if (j === 'timestamp') {
              return parseTime(v[j])
            } else {
              return v[j]
            }
          }))
        },
        //新增会员对话框打开
        addUserCard()
        {
          this.addVisible = true;
          this.title="新增会员";
        },
        /*query展开和收起*/
        toggleAdvanced()
        {
          this.advanced = !this.advanced;
        },

        //会员的启用或者停用
        handleUse(row)
        {
          let that = this
          if(row.status === "1")//代表启用
          {
            this.$confirm("您要停用会员"+row.name+"吗?").then(function()
            {
              row.status = "0";//改为停用
              userCard.updateUserCard(row).then((response)=>
              {
                if(response.code === 200)
                {
                  that.$message.success("停用成功!");
                }else
                {
                  that.$message.error("停用失败，请联系管理员!");
                }
              })
            })
          }
          if(row.status === "0")//代表停用
          {
            this.$confirm("您要启用会员"+row.name+"吗?").then(function()
            {
              row.status = "1";//改为启用
              userCard.updateUserCard(row).then((response)=>
              {
                if(response.code === 200)
                {
                  that.$message.success("启用成功!");
                }else
                {
                  that.$message.error("启用失败，请联系管理员!");
                }
              })
            })
          }
        },
        //重置会员卡
        resetUserCardQuery()
        {
          this.userCardQuery =
            {
              name:"",
              mobile:""
            };
          this.getUserCardList();
        },
        //查询参与人
        submitUserCardQuery()
        {
          if(!this.advanced)
          {
            this.advanced = !this.advanced;
          }
          this.getUserCardList();
        },

        //获取会员卡列表
        getUserCardList(currentPage = 1)
        {
          let that = this;
          this.queryParams.currentPage = currentPage;
          this.isLoading = true;
          userCard.pageUserCardCondition(this.queryParams.currentPage,this.queryParams.limit,this.userCardQuery)
            .then(response=>
            {
              this.userCardList = response.data.rows;
              this.userCardListTotal = response.data.total;
              this.isLoading = false;
            }).catch(error => {
            this.isLoading = false;
            that.$message.error(error);})
        },
        //重置积分明细查询条件
        resetIntegralQuery()
        {
          this.userIntegralQuery = {
            detail:"",
            integralNum:"",
            createTime:""
          };
          this.getIntegralList();
        },
        //获取积分明细列表
        getIntegralList(currentPage = 1)
        {
          let that = this;
          this.IntegralQueryParams.currentPage = currentPage;
          this.isLoading = true;
          integral.getIntegralDetail(this.cardNum,this.IntegralQueryParams.currentPage,this.IntegralQueryParams.limit,this.userIntegralQuery)
            .then((response)=>
          {
            this.integralList = response.data.rows;
            this.integralListTotal = response.data.total;
            this.isLoading = false;
          }).catch(error => {
            this.isLoading = false;
            that.$message.error(error);})
        },

        //通过id删除会员卡
        removeUserCard(row)
        {
          let id = row.id;
          let that = this;
          that.$confirm("是否确认删除会员"+row.name+"的数据项?").then(function()
          {
            userCard.deleteUserCardById(id).then((response)=>
            {
              if(response.code === 200)
              {
                that.$message.success("删除成功！");
                that.getUserCardList();
              }else
              {
                that.$message.error("删除失败！");
              }
            }).catch(error=> {
              console.log(error)
            })
          })
        },
        //关闭积分明细查询框
        queryUserIntegralCancel()
        {
          this.queryUserIntegralVisible= false;
          this.userIntegralQuery = {
            detail:"",
            integralNum:"",
            createTime:""
          };
          this.cardNum = "";
        },
        //关闭积分明细查询框
        closeUserCard()
        {
          this.queryUserIntegralVisible= false;
          this.userIntegralQuery = {
            detail:"",
            integralNum:"",
            createTime:""
          };
          this.cardNum = "";
        },
        //关闭修改会员框
        updateActCancel()
        {
          this.updateVisible = false;
        },
        //关闭新增会员框
        addActCancel()
        {
          this.addVisible = false;
        },

        //点击修改会员卡对话框
        updateUserCard(row)
        {
          this.updateVisible = true;
          this.title="修改会员";
          this.updateForm.id = row.id;
          this.updateForm.name = row.name;
          this.updateForm.openCardTime = row.openCardTime;
          this.updateForm.cardType = row.cardType;
          this.updateForm.cardNum = row.cardNum;
          this.updateForm.mobile = row.mobile;
          this.updateForm.sex = row.sex ==="0"?"男":"女";
          this.updateForm.status = row.status==="0"?"停用":"启用";
        },

        //提交会员卡的新增
        submitAddUserCard()
        {
          this.$refs['addForm'].validate((valid) =>
          {
            if(valid)
            {
              this.addForm.sex = this.addForm.sex==="男"?"0":"1";
              this.addForm.status = this.addForm.status==="停用"?"0":"1";
              userCard.addUserCard(this.addForm).then((response)=>
              {
                if(response.code === 200)
                {
                  this.$message.success("新增成功!");
                }else
                {
                  this.$message.error("新增失败!");
                }
              });
              this.addVisible = false;
              this.title="";
              this.addForm =
                {
                  name:"",
                  openCardTime:"",
                  cardType:"",
                  cardNum:"",
                  mobile:"",
                  sex:"",
                  status:""
                };
              this.getUserCardList();
            }
          });
        },

        //提交会员卡的修改
        submitUpdateUserCard()
        {
          this.$refs['updateForm'].validate((valid) =>
          {
            if(valid)
            {
              this.updateForm.sex = this.updateForm.sex==="男"?"0":"1";
              this.updateForm.status = this.updateForm.status==="停用"?"0":"1";
              userCard.updateUserCard(this.updateForm).then((response)=>
              {
                if(response.code === 200)
                {
                  this.$message.success("修改成功!");
                  this.getUserCardList();
                }else
                {
                  this.$message.error("修改失败!");
                }
              });
              this.updateVisible = false;
              this.title="";
              this.updateForm =
              {
                name:"",
                openCardTime:"",
                cardType:"",
                cardNum:"",
                mobile:"",
                sex:"",
                status:""
              };
              this.getUserCardList();
            }
          });
        },

        //关闭会员卡的修改
        updateUserCardCancel()
        {
          this.updateVisible = false;
          this.title="";
          this.updateForm =
          {
            name:"",
            openCardTime:"",
            cardType:"",
            cardNum:"",
            mobile:"",
            sex:"",
            status:""
          };
        },
        //关闭会员卡的新增
        addUserCardCancel()
        {
          this.addVisible = false;
          this.title="";
          this.addForm =
            {
              name:"",
              openCardTime:"",
              cardType:"",
              cardNum:"",
              mobile:"",
              sex:"",
              status:""
            };
        }
      },

    created()
    {
      this.getUserCardList();
    }
  }
</script>

<style>
  .table-page-search-submitButtons
  {
    height: 50px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }

</style>

